<template>
  <div class="edit">

    <customer-tag-notice :customerTagArr="customerTagArr"></customer-tag-notice>

    <van-overlay :show="overlayShow" :z-index="1000">
      <div style="display: flex;align-items: center;justify-content: center;height: 100%;">
        <van-loading type="spinner" color="#1989fa">请稍候...</van-loading>
      </div>
    </van-overlay>
    <div style="margin-bottom: 10vh;">
      <van-collapse v-model="activeNames">
        <van-collapse-item size="large" v-for="item in jsondata.head" :key="item.grouptitle" :name="item.grouptitle"
          :title="item.grouptitle">
          <van-cell-group style="border:0px;">
            <div style="border-bottom:1px solid #ebedf0" v-for="itemdata in item.groupvalue" :key="itemdata.ID">
              <idatetime ishead :itemdata="itemdata"
                v-if="itemdata.sUIType == 'datetime' || itemdata.sUIType == 'yearmonth'" @dateChange="dateChange"
                :jsondata="jsondata" />
              <icode @handleFiledLink="handleFiledLink" ishead :itemdata="itemdata"
                v-else-if="itemdata.sUIType == 'code'" />
              <ienum @handleFiledLink="handleFiledLink" ishead :itemdata="itemdata"
                v-else-if="itemdata.sUIType == 'enum'" :jsondata="jsondata" :idobject="idobject" />
              <iref @handleFiledLink="handleFiledLink" ishead :itemdata="itemdata" :fromcardid="fromcardid"
                v-else-if="itemdata.sUIType == 'ref'" :clickmodel.sync="clickmodel" :clickfrom.sync="clickfrom"
                :clickindexName.sync="clickindexName" :clickindex.sync="clickindex" :jsondata="jsondata"
                :activeNames="activeNames" :updateCustomerTagArr="updateCustomerTagArr" />
              <ibool @handleFiledLink="handleFiledLink" ishead :itemdata="itemdata"
                v-else-if="itemdata.sUIType == 'bool'" :jsondata="jsondata" :idobject="idobject" />
              <ifile ishead :itemdata="itemdata" v-else-if="itemdata.sUIType == 'file'" :jsondata="jsondata" />
              <ipicture ishead :itemdata="itemdata" v-else-if="itemdata.sUIType == 'picture'" :jsondata="jsondata" />
              <istring @handleFiledLink="handleFiledLink" ishead :itemdata="itemdata"
                v-else-if="itemdata.sUIType == 'string'" :jsondata="jsondata" :idobject="idobject" />
              <imap ishead :itemdata="itemdata" v-else-if="itemdata.sUIType == 'map'" :jsondata="jsondata"
                :item="item" />
              <istring @handleFiledLink="handleFiledLink" ishead :itemdata="itemdata" v-else :jsondata="jsondata"
                :idobject="idobject" />
            </div>
          </van-cell-group>
        </van-collapse-item>
      </van-collapse>
      <!-- <div v-for="(itembody, indexName) in jsondata.body" :key="indexName" :name="indexName" :title="indexName">
        <van-collapse v-model="activeBodyNams">
          <van-collapse-item size="large" v-for="(item, index) in jsondata.bodydata[indexName]" :key="indexName + index" :name="indexName + index" :title="detailTitle(indexName, item, index)">
            <van-cell-group style="border:0px;">
              <div style="border-bottom:1px solid #ebedf0" v-for="itemdata in item" :key="itemdata.ID">
                <idatetime :index="index" :itemdata="itemdata" v-if="itemdata.sUIType == 'datetime'" />
                <icode @handleFiledLink="handleFiledLink" :index="index" :itemdata="itemdata" v-else-if="itemdata.sUIType == 'code'" />
                <ienum @handleFiledLink="handleFiledLink" :index="index" :itemdata="itemdata" v-else-if="itemdata.sUIType == 'enum'" :jsondata="jsondata" :idobject="idobject" />
                <iref @handleFiledLink="handleFiledLink" :index="index" :itemdata="itemdata" v-else-if="itemdata.sUIType == 'ref'" :clickmodel.sync="clickmodel" :clickfrom.sync="clickfrom" :clickindexName.sync="clickindexName" :clickindex.sync="clickindex" :jsondata="jsondata" :indexName="indexName" />
                <ibool @handleFiledLink="handleFiledLink" :index="index" :itemdata="itemdata" v-else-if="itemdata.sUIType == 'bool'" :jsondata="jsondata" :idobject="idobject" />
                <ifile :index="index" :itemdata="itemdata" v-else-if="itemdata.sUIType == 'file'" :jsondata="jsondata" />
                <ipicture :index="index" :itemdata="itemdata" v-else-if="itemdata.sUIType == 'picture'" :jsondata="jsondata" />
                <istring @handleFiledLink="handleFiledLink" :index="index" :itemdata="itemdata" v-else-if="itemdata.sUIType == 'string'" :jsondata="jsondata" :indexName="indexName" :idobject="idobject" />
                <imap :index="index" :itemdata="itemdata" v-else-if="itemdata.sUIType == 'map'" :jsondata="jsondata" :item="item" />
                <istring @handleFiledLink="handleFiledLink" :index="index" :itemdata="itemdata" v-else :jsondata="jsondata" :indexName="indexName" :idobject="idobject" />
              </div>
              <van-button type="danger" size="small" block style="font-size:14px; font-weight:bold;background-color: #fff;color:#ff4d4f; border-color: #fff" @click="delRow(indexName, index)">- 删除{{ indexName }}{{ index + 1 }}</van-button>
            </van-cell-group>
          </van-collapse-item>
        </van-collapse>
        <van-button v-show="jsondata.hasdetail === '1'" size="large" plain style="color:#039be5 ;border-color: #fff" @click="addRow(indexName)">+ 增加明细</van-button>
      </div> -->
      <!-- 子表 -->
      <body-data :jsondata="jsondata" :detailTitle="detailTitle" :activeBodyNams="activeBodyNams"
        :clickmodel.sync="clickmodel" :clickfrom.sync="clickfrom" :handleFiledLink="handleFiledLink"
        :clickindexName.sync="clickindexName" :clickindex.sync="clickindex" :addRow="addRow"
        :delRow="delRow"></body-data>



    </div>
    <van-tabbar v-model="active" safe-area-inset-bottom>
      <van-tabbar-item @click="save">保存</van-tabbar-item>
      <!-- <van-tabbar-item @click="savesubmit">保存并提交</van-tabbar-item> -->
    </van-tabbar>
  </div>
</template>

<script>
import Vue from 'vue'
import { Swipe, SwipeItem, Panel, Dialog, Search, List, Cell, PullRefresh, Toast, Tabbar, TabbarItem, Popup, DatetimePicker, ActionSheet, Tab, Tabs, Collapse, CollapseItem, Checkbox, CheckboxGroup, Uploader, Overlay, Loading, Rate, NumberKeyboard } from 'vant'
import qs from 'qs'
import useInput from '@/utils/useinput'
import * as dd from 'dingtalk-jsapi'
import { fieldLinkMixins } from '@/mixins/fieldLink.js'
import { fieldMapMixins } from '@/mixins/fieldmap.js'
import { eventCommonMixins } from '@/mixins/eventCommon.js'
import { labelBaseMonthMixins } from "@/mixins/labelBaseMonth.js";
import bodyData from '@/components/bodyData/bodyData'
import CustomerTagNotice from '@/components/CustomerTagNotice'
Vue.use(Panel).use(Dialog).use(useInput).use(Search).use(List).use(Cell).use(PullRefresh).use(Toast).use(Tabbar).use(TabbarItem).use(Popup).use(DatetimePicker).use(ActionSheet).use(Tab).use(Tabs).use(Collapse).use(CollapseItem).use(Checkbox).use(CheckboxGroup).use(Uploader).use(Overlay).use(Loading).use(Rate).use(NumberKeyboard)
export default {
  components: {
    "body-data": bodyData,
    "customer-tag-notice": CustomerTagNotice
  },
  name: 'edit',
  mixins: [fieldLinkMixins, fieldMapMixins, eventCommonMixins, labelBaseMonthMixins],
  data() {
    return {
      idobject: this.$route.query.idobject,
      jsondata: {
        bodydata: {},
        body: [],
        bodymetadata: {},
        headmetadata: {}
      },
      index: 0,
      active: 0,
      activeNames: [''],
      activeBodyNams: [''],
      clickmodel: {},
      clickindexName: '',
      isLoad: false,
      clickfrom: '',
      clickindex: 0,
      isDisable: false,
      overlayShow: false,
      isDirectConnection: false,
      fromcardid: this.$route.query.fromcardid,
    }
  },
  watch: {
    isDirectConnection(value) {
      if (!value) {
        this.handleFiledNoMust()
      }
    }
  },

  computed: {
    mydata() {
      // //console.log('jsondata', this.jsondata)
      // //console.log('head', this.jsondata.head)
      //console.log('starting mydata')
      let flag = false
      this.isDirectConnection = false
      for (let i = 0; this.jsondata.head && i < this.jsondata.head.length; i++) {
        let gv = this.jsondata.head[i].groupvalue
        for (let j = 0; gv && j < gv.length; j++) {
          if (gv[j].sField == 'isdls1' && gv[j].value == '是') {
            flag = true
            this.isDirectConnection = true
            break
          }
        }
      }
      //console.log('flag', flag)

      let newhead = []
      newhead = this.jsondata.head.filter(item => {
        if (flag) {
          // if (item.grouptitle === '直连信息') {
          // }
          return true
        }

        if (!flag) {
          // if (item.grouptitle === '直连信息') {
          //   item.groupvalue.forEach(i => {
          //     i.lMustInput = '0'
          //   })
          // }
          return item.grouptitle != '直连信息'
        }
      })
      return newhead
    }
  },
  created() {
    //console.log('created......')
    // this.fetchData()
    let _this = this
    document.title = this.$route.query.stitle
    //console.log('document.title', document.title)
    if (dd.env.platform !== 'notInDingTalk') {
      dd.ready(function () {
        dd.biz.navigation.setTitle({
          title: _this.$route.query.stitle
        })
      })
    }
  },
  mounted: function () {
    //console.log('edit ...')
    //console.log('start created')
    document.title = this.$route.query.stitle
    if (!this.isLoad) {
      let data = { [this.idobject + '_id']: this.$route.query.itemid }
      this.axios({
        method: 'post',
        url: '/api/' + this.idobject + '.edit.do',
        data: qs.stringify(data)
      }).then(res => {
        //console.log(res)
        if (res.data.flag === '1') {
          Toast(res.data.des)
          if (res.data.des && res.data.des.indexOf('登录过期') >= 0) {
            this.loginout()
          }
        } else {
          this.jsondata = res.data.jsondata


          // 字段联动变量
          this.orginData = JSON.parse(JSON.stringify(this.jsondata))
          this.controlLinkArr = this.getFieldLink(this.jsondata)

          if (this.jsondata.hasdetail != '0') {
            this.controlLinkArrDetail = this.getFieldLinkDetail(this.jsondata)
          }

          // 字段联动初始化
          this.firstHandleFiledLink(this.jsondata)


          for (let i = 0; i < res.data.jsondata.head.length; i++) {
            let itemgroup = this.jsondata.head[i].groupvalue
            for (let itemindex in itemgroup) {
              let itemdata = itemgroup[itemindex]
              if (itemdata.sUIType === 'datetime' && itemdata.sUITypeExp !== 'long') {
                itemdata.value = itemdata.value.substring(0, 10)
              }
            }
            this.activeNames.push(res.data.jsondata.head[i].grouptitle)
          }
          //console.log(this.jsondata)
          this.isLoad = true
        }
      }).catch(res => {
        this.reserror(res)
      })
    }
  },
  methods: {
    handleFiledNoMust() {
      this.jsondata.head = this.jsondata.head.map(item => {
        if (item.grouptitle === '直连信息') {
          for (let i = 0; i < item.groupvalue.length; i++) {
            item.groupvalue[i].value = ''
            item.groupvalue[i].lMustInput = '0'
          }
          return item
        } else {
          return item
        }
      })
    },
    detailTitle(indexName, item, index) {
      for (let i = 0; i < item.length; i++) {
        if (item[i].sField == this.jsondata.titleField) {
          return (index + 1) + '.' + (item[i].value.length > 0 ? item[i].value : '新' + indexName)
        }
      }
      return indexName + (index + 1)
    },
    save() {
      if (!this.isDisable) {
        this.overlayShow = true
        this.isDisable = true
        let data = {}
        data[this.idobject + '_id'] = this.$route.query.itemid
        for (let groupindex in this.jsondata.head) {
          let itemgroup = this.jsondata.head[groupindex].groupvalue
          for (let itemindex in itemgroup) {
            let itemdata = itemgroup[itemindex]
            if (itemdata.sUIType === 'ref') {
              data[itemdata.idObject + '_' + itemdata.sField] = itemdata.valuehidden
              data[itemdata.idObject + '_' + itemdata.sField + '_ref'] = itemdata.value
            } else if (itemdata.sUIType === 'enum') {
              data[itemdata.idObject + '_' + itemdata.sField] = itemdata.valuehidden
              data[itemdata.idObject + '_' + itemdata.sField + '_enum'] = itemdata.value
            } else if (itemdata.sUIType === 'file' || itemdata.sUIType === 'picture') {
              data[itemdata.idObject + '_' + itemdata.sField] = itemdata.valuehidden
              data[itemdata.idObject + '_' + itemdata.sField + '_title'] = itemdata.value
            } else {
              data[itemdata.idObject + '_' + itemdata.sField] = itemdata.value
            }
          }
        }
        for (let indexName in this.jsondata.bodydata) {
          for (let i = 0; i < this.jsondata.bodydata[indexName].length; i++) {
            let item = this.jsondata.bodydata[indexName][i]
            for (let itemindex in item) {
              let itemdata = item[itemindex]
              if (itemdata.sUIType === 'ref') {
                data[i + '_' + itemdata.idObject + '_' + itemdata.sField] = itemdata.valuehidden
                data[i + '_' + itemdata.idObject + '_' + itemdata.sField + '_ref'] = itemdata.value
              } else if (itemdata.sUIType === 'enum') {
                data[i + '_' + itemdata.idObject + '_' + itemdata.sField] = itemdata.valuehidden
                data[i + '_' + itemdata.idObject + '_' + itemdata.sField + '_enum'] = itemdata.value
              } else if (itemdata.sUIType === 'file' || itemdata.sUIType === 'picture') {
                data[i + '_' + itemdata.idObject + '_' + itemdata.sField] = itemdata.valuehidden
                data[i + '_' + itemdata.idObject + '_' + itemdata.sField + '_title'] = itemdata.value
              } else {
                data[i + '_' + itemdata.idObject + '_' + itemdata.sField] = itemdata.value
              }
            }
          }
        }
        this.axios({
          method: 'post',
          url: '/api/' + this.idobject + '.editsave.do',
          data: qs.stringify(data)
        }).then(res => {
          this.isDisable = false
          this.overlayShow = false
          if (res.data.flag === '0') {
            Toast('保存成功')
            /* if (this.$route.query.fromobject && this.$route.query.fromcardid) {
              this.$router.push({ name: 'card', query: { idobject: this.$route.query.fromobject, itemid: this.$route.query.fromcardid } })
            } else {
              this.$router.push({ name: 'list', query: { idobject: this.idobject } })
            } */
            this.$router.go(-1)
          } else {
            Toast(res.data.des)
            if (res.data.des && res.data.des.indexOf('登录过期') >= 0) {
              this.loginout()
            }
          }
          //console.log(res)
        }).catch(res => {
          this.isDisable = false
          this.overlayShow = false
          //console.log(res)
        })
      }
    },
    savesubmit() {
      Toast('submit')
    },
    addRow(indexName) {
      let bodycopy = JSON.parse(JSON.stringify(this.jsondata.body[indexName]))
      bodycopy.forEach((iv) => {
        iv.copyTitle = iv.sTitle
        iv.sTitle = this.replaceNWithMonth(iv.sTitle, this.monthMix);
      });
      this.jsondata.bodydata[indexName].push(bodycopy)
      this.orginData.bodydata[indexName].push(bodycopy)
    },
    delRow(indexName, index) {
      if (this.jsondata.bodydata[indexName].length === 1) {
        Toast('至少保留一条表体行，不能删除！')
        return
      }
      Dialog.confirm({
        title: '',
        message: '你确定要删除' + indexName + ' ' + (index + 1) + '吗?'
      })
        .then(() => {
          // on confirm
          this.jsondata.bodydata[indexName].splice(index, 1)
        })
        .catch(() => {
          // on cancel
        })
    }
    // handleRefMap (mode, data, refmap) {
    //   const mapField = []
    //   let mapObjectStr = this.$store.state.ref_toobject
    //   for (let key in refmap) {
    //     if (key.indexOf('_ref.') == -1) {
    //       const fieldArr = key.split('_')
    //     mapField.push(fieldArr[1])
    //     }
    //   }

    //   if (mode === 'headdata') {
    //     for (let i = 0; i < data.length; i++) {
    //       for (let j = 0; j < data[i].groupvalue.length; j++) {
    //         if (mapField.indexOf(data[i].groupvalue[j].sField) !== -1) {
    //           switch (data[i].groupvalue[j].sUIType) {
    //             case 'ref':
    //               data[i].groupvalue[j].value = refmap[`${mapObjectStr}_${data[i].groupvalue[j].sField}_ref`]
    //               data[i].groupvalue[j].valuehidden = refmap[`${mapObjectStr}_${data[i].groupvalue[j].sField}`]
    //               break
    //             case 'enum':
    //               data[i].groupvalue[j].value = refmap[`${mapObjectStr}_${data[i].groupvalue[j].sField}_enum`]
    //               data[i].groupvalue[j].valuehidden = refmap[`${mapObjectStr}_${data[i].groupvalue[j].sField}`]
    //               break
    //             case 'bool':
    //               data[i].groupvalue[j].value = refmap[`${mapObjectStr}_${data[i].groupvalue[j].sField}`] == '1' ? '是' : '否'
    //               break
    //             default:
    //               data[i].groupvalue[j].value = refmap[`${mapObjectStr}_${data[i].groupvalue[j].sField}`]
    //               break
    //           }
    //         }
    //       }
    //     }
    //   }
    //   if (mode === 'bodydata') {
    //     for (let i = 0; i < data.length; i++) {
    //       if (mapField.indexOf(data[i].sField) !== -1) {
    //         switch (data[i].sUIType) {
    //           case 'ref':
    //             data[i].value = refmap[`${mapObjectStr}_${data[i].sField}_ref`]
    //             data[i].valuehidden = refmap[`${mapObjectStr}_${data[i].sField}`]
    //             break
    //           case 'enum':
    //             data[i].value = refmap[`${mapObjectStr}_${data[i].sField}_enum`]
    //             data[i].valuehidden = refmap[`${mapObjectStr}_${data[i].sField}`]
    //             break
    //           case 'bool':
    //             data[i].value = refmap[`${mapObjectStr}_${data[i].sField}`] === '1' ? '是' : '否'
    //             break
    //           default:
    //             data[i].value = refmap[`${mapObjectStr}_${data[i].sField}`]
    //             break
    //         }
    //       }
    //     }
    //   }
    // }

  }
  // activated () {
  //   //console.log(this.$store.state.ref_show)
  //   //console.log(this.$store.state.ref_id)
  //   if (this.$store.state.ref_show !== '') {
  //     this.clickmodel.value = this.$store.state.ref_show
  //     this.clickmodel.valuehidden = this.$store.state.ref_id
  //     this.clickmodel.errormsg = ''

  //     if (this.$store.state.ref_map) {
  //       if (this.clickfrom === 'headdata') {
  //         this.handleRefMap('headdata', this.jsondata.head, this.$store.state.ref_map)
  //       } else if (this.clickfrom === 'bodydata') {
  //         this.handleRefMap('bodydata', this.jsondata.bodydata[this.clickindexName][this.clickindex], this.$store.state.ref_map)
  //       }
  //     }

  //     this.clickmodel = {}
  //     this.clickindex = 0
  //     this.clickindexName = ''
  //     this.clickfrom = ''
  //     this.$store.commit('clearRef')

  //     /* this.clickmodel.value = this.$store.state.ref_show
  //     this.clickmodel.valuehidden = this.$store.state.ref_id
  //     let fieldmap = this.clickmodel.fieldmap
  //     if (fieldmap !== undefined && fieldmap.length > 0) {
  //       let arrFieldmap = fieldmap.split(';')
  //       let item = this.$store.state.ref_item
  //       if (this.clickfrom === 'headdata') {
  //         for (let groupindex = 0; groupindex < this.jsondata.head.length; groupindex++) {
  //           let itemgroup = this.jsondata.head[groupindex]
  //           for (let itemindex = 0; itemindex < itemgroup.groupvalue.length; itemindex++) {
  //             let itemdata = itemgroup.groupvalue[itemindex]
  //             for (let fieldmapindex in arrFieldmap) {
  //               let arrFieldMapKey = arrFieldmap[fieldmapindex].split(':')
  //               if (this.$store.state.ref_field === arrFieldMapKey[1]) {
  //                 continue
  //               }
  //               if (arrFieldMapKey.length === 3 && arrFieldMapKey[2] !== '' && this.$store.state.ref_field !== arrFieldMapKey[2]) {
  //                 continue
  //               }
  //               if (itemdata.sField === arrFieldMapKey[1]) {
  //                 if (itemdata.sUIType === 'ref') {
  //                   itemdata.value = item[arrFieldMapKey[0] + '_ref']
  //                   itemdata.valuehidden = item[arrFieldMapKey[0]]
  //                 } else if (itemdata.sUIType === 'enum') {
  //                   itemdata.value = item[arrFieldMapKey[0] + '_enum']
  //                   itemdata.valuehidden = item[arrFieldMapKey[0]]
  //                 } else {
  //                   itemdata.value = item[arrFieldMapKey[0]]
  //                 }
  //               }
  //             }
  //           }
  //         }
  //       } else if (this.clickfrom === 'bodydata') {
  //         for (let itemindex in this.jsondata.bodydata[this.clickindex]) {
  //           let itemdata = this.jsondata.bodydata[this.clickindex][itemindex]
  //           for (let fieldmapindex in arrFieldmap) {
  //             let arrFieldMapKey = arrFieldmap[fieldmapindex].split(':')
  //             if (this.$store.state.ref_field === arrFieldMapKey[1]) {
  //               continue
  //             }
  //             if (arrFieldMapKey.length === 3 && arrFieldMapKey[2] !== '' && this.$store.state.ref_field !== arrFieldMapKey[2]) {
  //               continue
  //             }
  //             if (itemdata.sField === arrFieldMapKey[1]) {
  //               if (itemdata.sUIType === 'ref') {
  //                 itemdata.value = item[arrFieldMapKey[0] + '_ref']
  //                 itemdata.valuehidden = item[arrFieldMapKey[0]]
  //               } else if (itemdata.sUIType === 'enum') {
  //                 itemdata.value = item[arrFieldMapKey[0] + '_enum']
  //                 itemdata.valuehidden = item[arrFieldMapKey[0]]
  //               } else {
  //                 itemdata.value = item[arrFieldMapKey[0]]
  //               }
  //             }
  //           }
  //         }
  //       }
  //     }
  //     this.clickmodel = {}
  //     this.clickindex = 0
  //     this.clickfrom = ''
  //     this.$store.commit('clearRef') */
  //   }
  // }
}
</script>

<style scoped>
.fieldgroup_title {
  text-align: left;
  margin: 0px;
  padding: 25px 15px 15px;
  color: rgba(69, 90, 100, 0.6);
  font-weight: normal;
  font-size: 14px;
}
</style>
